package com.kxmall.web.controller.huishou;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.kxmall.common.annotation.Log;
import com.kxmall.common.annotation.RepeatSubmit;
import com.kxmall.common.core.controller.BaseController;
import com.kxmall.common.core.domain.PageQuery;
import com.kxmall.common.core.domain.R;
import com.kxmall.common.core.page.TableDataInfo;
import com.kxmall.common.core.validate.AddGroup;
import com.kxmall.common.enums.BusinessType;
import com.kxmall.common.enums.RiderLoginType;
import com.kxmall.common.enums.RiderWorkStateType;
import com.kxmall.common.enums.RoleStatusType;
import com.kxmall.common.utils.poi.ExcelUtil;
import com.kxmall.huishou.domain.bo.HsRecyclerApplyBo;
import com.kxmall.huishou.domain.vo.HsRecyclerApplyVo;
import com.kxmall.huishou.service.IHsRecyclerApplyService;
import com.kxmall.rider.domain.KxRider;
import com.kxmall.rider.domain.KxRiderCycle;
import com.kxmall.rider.domain.vo.KxRiderVo;
import com.kxmall.rider.mapper.KxRiderCycleMapper;
import com.kxmall.rider.mapper.KxRiderMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 回收员申请信息
 *
 * @author kxmall
 * @date 2023-11-24
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/huishou/recyclerApply")
public class HsRecyclerApplyController extends BaseController {

    private final IHsRecyclerApplyService iHsRecyclerApplyService;
    private final KxRiderMapper kxRiderMapper;
    private final KxRiderCycleMapper  kxRiderCycleMapper;
    /**
     * 查询回收员申请信息列表
     */
    @SaCheckPermission("huishou:recyclerApply:list")
    @GetMapping("/list")
    public TableDataInfo<HsRecyclerApplyVo> list(HsRecyclerApplyBo bo, PageQuery pageQuery) {
        return iHsRecyclerApplyService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出回收员申请信息列表
     */
    @SaCheckPermission("huishou:recyclerApply:export")
    @Log(title = "回收员申请信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HsRecyclerApplyBo bo, HttpServletResponse response) {
        List<HsRecyclerApplyVo> list = iHsRecyclerApplyService.queryList(bo);
        ExcelUtil.exportExcel(list, "回收员申请信息", HsRecyclerApplyVo.class, response);
    }

    /**
     * 获取回收员申请信息详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("huishou:recyclerApply:query")
    @GetMapping("/{id}")
    public R<HsRecyclerApplyVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iHsRecyclerApplyService.queryById(id));
    }

    /**
     * 新增回收员申请信息
     */
    @SaCheckPermission("huishou:recyclerApply:add")
    @Log(title = "回收员申请信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody HsRecyclerApplyBo bo) {
        return toAjax(iHsRecyclerApplyService.insertByBo(bo));
    }

    /**
     * 审批申请信息
     */
    @SaCheckPermission("huishou:recyclerApply:edit")
    @Log(title = "回收员申请信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/edit")
    public R<Void> edit(@RequestBody HsRecyclerApplyBo bo) {
        if(bo == null || bo.getId() == null || bo.getStatus() == null ){
            return R.fail("参数错误");
        }

        HsRecyclerApplyVo hsRecyclerApplyVo = iHsRecyclerApplyService.queryById(bo.getId());
        if(hsRecyclerApplyVo == null || hsRecyclerApplyVo.getStatus() == null || hsRecyclerApplyVo.getStatus() != 0){
            return R.fail("申请信息不存在或者该状态不能进行审批");
        }
        Boolean boolStatus = iHsRecyclerApplyService.editByBo(bo);
        if (bo.getStatus() != 1) {
            return toAjax(boolStatus);
        }
        // 如果回收员存在，需要判定是否存在，如果不存在就新增，存在就修改
        KxRiderVo kxRiderVo = kxRiderMapper.selectVoById(hsRecyclerApplyVo.getUserId());
        if (kxRiderVo == null) {
            //如果审核通过，新增回收员用户信息
            addRiderUser();
        }

        if (kxRiderVo != null) {
            KxRider riderDO;
            Date now = new Date();
            riderDO = new KxRider();
            riderDO.setId(hsRecyclerApplyVo.getUserId());
            riderDO.setState(RoleStatusType.ACTIVE.getCode());
            riderDO.setUpdateTime(now);
            kxRiderMapper.updateById(riderDO);
        }

        return toAjax(boolStatus);
    }
    /**
     * 新增骑手用户
     */
    private void addRiderUser() {
        KxRider riderDO;
        Date now = new Date();
        riderDO = new KxRider();
        riderDO.setLoginType(RiderLoginType.REGISTER.getCode());
        riderDO.setWorkState(RiderWorkStateType.REST.getCode());
        riderDO.setState(RoleStatusType.ACTIVE.getCode());

        riderDO.setDeliveryStart("8:30");
        riderDO.setDeliveryEnd("23:00");
        riderDO.setUpdateTime(now);
        riderDO.setCreateTime(now);
        riderDO.setStorageId(11L);
        kxRiderMapper.insert(riderDO);

        //上班周期
        for (int i = 0; i < 7; i++) {
            KxRiderCycle riderCycleDO = new KxRiderCycle();
            riderCycleDO.setRiderId(riderDO.getId());
            riderCycleDO.setWeekNumber((long) (i + 1));
            kxRiderCycleMapper.insert(riderCycleDO);
        }
    }
    /**
     * 删除回收员申请信息
     *
     * @param ids 主键串
     */
    @SaCheckPermission("huishou:recyclerApply:remove")
    @Log(title = "回收员申请信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iHsRecyclerApplyService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
